<?php

  require_once('library/googleresponse.php');
  //require_once('library/googlemerchantcalculations.php');
  require_once('library/googleresult.php');
  require_once('library/googlelog.php');
  require_once('library/googlerequest.php');
  require_once('includes/constants.php');
  require_once('includes/common.php');
  
  //$debugLog = new GoogleLog("debug.log", "debugError.log", L_ALL);
  
  define('RESPONSE_HANDLER_ERROR_LOG_FILE', 'googleerror.log');
  define('RESPONSE_HANDLER_LOG_FILE', 'googlemessage.log');

  $merchant_id = GOOGLE_MERCHANT_ID; 
  $merchant_key = GOOGLE_MERCHANT_KEY;   
  $server_type = "sandbox";  
  $currency = 'GBP';  

  $Gresponse = new GoogleResponse($merchant_id, $merchant_key);
  $Grequest = new GoogleRequest($merchant_id, $merchant_key, $server_type, $currency);
  //Setup the log file
  $Gresponse->SetLogFiles(RESPONSE_HANDLER_ERROR_LOG_FILE, 
                                        RESPONSE_HANDLER_LOG_FILE, L_ALL);
  // Retrieve the XML sent in the HTTP POST request to the ResponseHandler
  $xml_response = isset($HTTP_RAW_POST_DATA)?
                    $HTTP_RAW_POST_DATA:file_get_contents("php://input");
  if (get_magic_quotes_gpc()) {
    $xml_response = stripslashes($xml_response);
  }
  list($root, $data) = $Gresponse->GetParsedXML($xml_response);
  $Gresponse->SetMerchantAuthentication($merchant_id, $merchant_key);

  $status = $Gresponse->HttpAuthentication();
  if(! $status) {
    die('authentication failed');
  }

  switch ($root) {
    case "request-received": {
      break;
    }
    case "error": {
      break;
    }
    case "diagnosis": {
      break;
    }
    case "checkout-redirect": {
      break;
    }
    case "merchant-calculation-callback": {
      break;
    }
    case "new-order-notification": {
        $Gresponse->SendAck(false);
		require_once('newOrderProcessingLogic.php');
      break; 
    }
    case "order-state-change-notification": {
      $Gresponse->SendAck(false);
      $new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
/*
The <financial-order-state> tag identifies the financial status of an order. Valid values for this tag are:

REVIEWING - Google Checkout is reviewing the order.
CHARGEABLE - The order is ready to be charged.
CHARGING - The order is being charged; you may not refund or cancel an order until is the charge is completed.
CHARGED - The order has been successfully charged; if the order was only partially charged, the buyer's account page will reflect the partial charge.
PAYMENT_DECLINED - The charge attempt failed.
CANCELLED - Either the buyer or the seller canceled the order. An order's financial state cannot be changed after the order is canceled. Learn more about when an order may be canceled.
CANCELLED_BY_GOOGLE - Google canceled the order. Google may cancel orders due to a failed charge without a replacement credit card being provided within a set period of time or due to a failed risk check. If Google cancels an order, you will be notified of the reason the order was canceled in the <reason> tag of an <order-state-change-notification>.
 */	  
      $new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];
/*	  
The <fulfillment-order-state> tag indicates the status of an order in the order handling process. Valid values for this tag are:

NEW - The order has been received but not prepared for shipping.
PROCESSING - The order is being prepared for shipping.
DELIVERED - The seller has shipped the order.
WILL_NOT_DELIVER - The seller will not ship the order; this status is used for canceled orders.
*/
	  $google_order_number = $data[$root]['google-order-number']['VALUE'];
	  updateOrderStatus($google_order_number, $new_fulfillment_order, $new_financial_state);
      switch($new_financial_state) {
        case 'REVIEWING': {
          break;
        }
        case 'CHARGEABLE': {
          //$Grequest->SendProcessOrder($data[$root]['google-order-number']['VALUE']);
          //$Grequest->SendChargeOrder($data[$root]['google-order-number']['VALUE'],'');
          break;
        }
        case 'CHARGING': {
          break;
        }
        case 'CHARGED': {
          break;
        }
        case 'PAYMENT_DECLINED': {
          break;
        }
        case 'CANCELLED': {
          break;
        }
        case 'CANCELLED_BY_GOOGLE': {
          //$Grequest->SendBuyerMessage($data[$root]['google-order-number']['VALUE'],
          //    "Sorry, your order is cancelled by Google", true);
          break;
        }
        default:
          break;
      }

      switch($new_fulfillment_order) {
        case 'NEW': {
          break;
        }
        case 'PROCESSING': {
          break;
        }
        case 'DELIVERED': {
          break;
        }
        case 'WILL_NOT_DELIVER': {
          break;
        }
        default:
          break;
      }
      break;
    }
    case "charge-amount-notification": {
      //$Grequest->SendDeliverOrder($data[$root]['google-order-number']['VALUE'],
      //    <carrier>, <tracking-number>, <send-email>);
      //$Grequest->SendArchiveOrder($data[$root]['google-order-number']['VALUE'] );
      $Gresponse->SendAck(false);
      break;
    }
    case "chargeback-amount-notification": {
      $Gresponse->SendAck(false);
      break;
    }
    case "refund-amount-notification": {
      $Gresponse->SendAck(false);
      break;
    }
    case "risk-information-notification": {
      $Gresponse->SendAck(false);
      break;
    }
    default:
      $Gresponse->SendBadRequestStatus("Invalid or not supported Message");
      break;
  }
  /* In case the XML API contains multiple open tags
     with the same value, then invoke this function and
     perform a foreach on the resultant array.
     This takes care of cases when there is only one unique tag
     or multiple tags.
     Examples of this are "anonymous-address", "merchant-code-string"
     from the merchant-calculations-callback API
  */
  function get_arr_result($child_node) {
    $result = array();
    if(isset($child_node)) {
      if(is_associative_array($child_node)) {
        $result[] = $child_node;
      }
      else {
        foreach($child_node as $curr_node){
          $result[] = $curr_node;
        }
      }
    }
    return $result;
  }

  /* Returns true if a given variable represents an associative array */
  function is_associative_array( $var ) {
    return is_array( $var ) && !is_numeric( implode( '', array_keys( $var ) ) );
  }
?>